<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高德地图轨迹展示</title>
    <style>
        body,
        html {
            margin: 0;
            padding: 0;
            height: 100%;
            font-family: Arial, sans-serif;
        }

        #container {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        #trajectoryMapContainer {
            flex: 1;
            width: 100%;
        }

        .control-panel {
            padding: 10px;
            background: #f5f5f5;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        button {
            padding: 5px 10px;
            cursor: pointer;
        }

        .time-slider {
            flex: 1;
            margin: 0 10px;
        }

        .custom-content-marker {
            position: relative;
            width: 48px;
            height: 71px;
        }

        .custom-content-marker img {
            width: 100%;
            height: 100%;
        }

        .close-btn {
            position: absolute;
            top: 0;
            right: 0;
            background: red;
            color: white;
            width: 16px;
            height: 16px;
            text-align: center;
            line-height: 16px;
            border-radius: 50%;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="container">
        <div id="trajectoryMapContainer"></div>
        <div class="control-panel">
            <button id="playBtn">播放</button>
            <button id="pauseBtn">暂停</button>
            <button id="stopBtn">停止</button>
            <select id="speedSelect">
                <option value="1">1x</option>
                <option value="2">2x</option>
                <option value="4">4x</option>
                <option value="8">8x</option>
            </select>
            <input type="range" id="timeSlider" class="time-slider" min="0" max="100" value="0">
            <span id="timeDisplay">00:00:00</span>
        </div>
    </div>

    <!-- 高德地图JS API -->
    <script src="https://webapi.amap.com/maps?v=2.0&key=6089b5b868160cd9820c162d02c1e10c"></script>
    <!-- 高德地图UI组件 -->
    <script src="https://webapi.amap.com/ui/1.1/main.js"></script>
    <script src="/lib/layui-v2.11.4/layui.js" charset="utf-8"></script>

    <script>
        layui.use(['form'], function () {
            var $ = layui.$;
            // 轨迹数据
            let trackData = [
                // {
                //     "trackTime": "2025-06-30 11:14:31",
                //     "id": 19501456338,
                //     "projectId": 1815,
                //     "tririgaUserCode": "585151326835589",
                //     "projectName": null,
                //     "source": "ZFY",
                //     "checkType": "GPS",
                //     "userId": 502999,
                //     "name": "裴井辉",
                //     "longitude": 116.313228,
                //     "latitude": 40.037606,
                //     "originalLongitude": 116.313228,
                //     "originalLatitude": 40.037606,
                //     "createTime": "2025-06-30 11:14:30",
                //     "labelId": "7235510156883177472",
                //     "pointId": null,
                //     "workIssueNum": 0,
                //     "gridId": "579517135029125",
                //     "gridName": "全网格巡查组",
                //     "originalGridId": "579517135029125",
                //     "originalGridName": "全网格巡查组",
                //     "ruleCoverageIds": "579517135029125,1832834465896038401",
                //     "locationTririgaCode": "579517135029125",
                //     "locationName": "全网格巡查组",
                //     "dottedFlag": 0,
                //     "angle": null,
                //     "speed": "0.0",
                //     "gpsStatus": null,
                //     "rssi": null,
                //     "mileage": null,
                //     "ble": null,
                //     "gnssNum": null,
                //     "dbName": "cityup_iot_v2",
                //     "tableName": "biz_user_track",
                //     "operationTs": "2025-06-30 11:14:30",
                //     "etlTimestamp": "2025-06-30 11:14:30",
                //     "gcsType": "GCJ-02",
                //     "devicePower": null
                // },
                // // 可以添加更多轨迹点数据...
                // {
                //     "trackTime": "2025-06-30 11:15:31",
                //     "longitude": 116.314228,
                //     "latitude": 40.038606,
                //     "speed": "1.0",
                //     "angle": 45,
                //     "devicePower": 80
                // },
                // {
                //     "trackTime": "2025-06-30 11:16:31",
                //     "longitude": 116.315228,
                //     "latitude": 40.039606,
                //     "speed": "2.0",
                //     "angle": 90,
                //     "devicePower": 75
                // }
            ];

            $.getJSON("/api/trackList.json", function (json) {
                console.log('json==', json)
                if (json.code === 0) {
                    trackData = json.data
                    // 初始化轨迹地图
                    new TrajectoryMap();
                } else {
                    console.error("数据加载失败:", json.msg);
                }
            });

            // 轨迹展示组件
            class TrajectoryMap {
                constructor() {
                    this.map = null;
                    this.pathSimplifier = null;
                    this.path = [];
                    this.pointList = [];
                    this.originDetailData = [];
                    this.currentDate = '2025-06-30';
                    this.navg1 = null;
                    this.startMarker = null;
                    this.endMarker = null;
                    this.mapMarker = null;
                    this.curIdx = 0;
                    this.navgStatus = 'default'; // playing, paused, default
                    this.timeSliderPosition = null;
                    this.isStartPolyLine = false;
                    this.passWayPolyline = null;

                    this.initMap();
                    this.initControls();
                }

                // 初始化地图
                initMap() {
                    // 中心点设置为第一个轨迹点

                    const center = trackData.length > 0 ? [trackData[0].longitude, trackData[0].latitude] : [116.397428, 39.90923];
                    console.log('center===', center)

                    this.map = new AMap.Map('trajectoryMapContainer', {
                        resizeEnable: true,
                        center: center,
                        zoom: 15,
                        animateEnable: true
                    });

                    console.log("开始初始化地图");

                    // 地图加载完成后初始化轨迹
                    this.map.on('complete', () => {
                        console.log("地图初始化完成");
                        this.initAMapUI();
                    });
                }

                // 加载高德地图UI组件
                initAMapUI() {
                    return new Promise((resolve) => {
                        console.log("开始加载PathSimplifier");
                        AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifier) => {
                            console.log("PathSimplifier加载完成");
                            if (!PathSimplifier.supportCanvas) {
                                alert('当前环境不支持 Canvas！');
                                return;
                            }
                            console.log("返回PathSimplifier======", PathSimplifier);
                            this.pathSimplifier = PathSimplifier;
                            this.afterMapMount();
                            resolve(PathSimplifier);
                        });
                    });
                }

                // 地图加载完成后执行
                afterMapMount() {
                    this.trajectoryFormat(trackData);
                    this.initTrajectory();
                    this.initMarker();
                    this.initEndMarker();
                }

                // 格式化轨迹数据
                trajectoryFormat(resData) {
                    this.pointList = [];
                    this.path = [];
                    this.originDetailData = [];

                    // 深拷贝数据
                    const data = JSON.parse(JSON.stringify(resData));

                    // 转换时间戳
                    data.forEach(item => {
                        item.trackTime = new Date(item.trackTime).getTime();
                    });

                    // 按时间排序
                    data.sort((a, b) => a.trackTime - b.trackTime);

                    // 计算当天开始时间戳
                    const startTimeStamp = new Date(this.currentDate).setHours(0, 0, 0, 0) / 1000;

                    data.forEach(item => {
                        const { longitude, latitude, labelId, trackTime, speed, angle, source, devicePower } = item;

                        if (longitude && latitude) {
                            const point = {
                                lng: longitude,
                                lat: latitude,
                                trackTime: trackTime,
                                second: trackTime / 1000 - startTimeStamp,
                                speed: speed,
                                angle: angle
                            };

                            const detailItem = {
                                ...item,
                                point: point,
                                trackTime: trackTime,
                                time: new Date(trackTime).toLocaleTimeString(),
                                issueNum: item.workIssueNum || 0,
                                sourceLabel: source || '',
                                source: source,
                                devicePower: devicePower,
                                labelId: labelId
                            };

                            this.originDetailData.push(detailItem);
                            this.path.push(point);
                            this.pointList.push([longitude, latitude]);
                        }
                    });
                    console.log('this.pointList===========',this.pointList)
                    console.log('this.path================',this.path)
                    console.log('this.originDetailData====',this.originDetailData)
                }

                // 初始化轨迹
                initTrajectory() {
                    if (!this.pathSimplifier || this.pointList.length === 0) return;

                    // 创建轨迹导航器
                    const pathSimplifierIns = new this.pathSimplifier({
                        zIndex: 100,
                        map: this.map,
                        getPath: () => this.pointList,
                        // getHoverTitle: (pathIndex, pointIndex) => {
                        //     return `${this.originDetailData[pointIndex].time}`;
                        // },
                        renderOptions: {
                            renderAllPointsIfNumberBelow: 100,
                            pathLineStyle: {
                                strokeStyle: '#3366ff',
                                lineWidth: 6,
                                dirArrowStyle: true
                            }
                        }
                    });

                    // 方案1：使用内置样式（最简单可靠）
                    this.navg1 = pathSimplifierIns.createPathNavigator(0, {
                        loop: false,
                        speed: 100,
                        pathNavigatorStyle: {
                            width: 16,
                            height: 16,
                            // content: PathSimplifier.Render.Canvas.getDefaultContent('arrow'),
                            fillStyle: '#3366FF',
                            strokeStyle: '#FFFFFF',
                            lineWidth: 2
                        }
                    });

                    // 巡航事件
                    this.navg1.on('move', (e) => {
                        this.curIdx = e.targetInfo.index;
                        this.timeSliderPosition = this.path[this.curIdx];

                        // 更新时间轴
                        document.getElementById('timeSlider').value = this.curIdx;
                        document.getElementById('timeDisplay').textContent =
                            this.originDetailData[this.curIdx].time;

                        if (this.curIdx === this.path.length - 1) {
                            this.setNavgEnd();
                        }
                    });

                    this.passWayPolyline = pathSimplifierIns;
                }
                // 初始化起点标记
                initMarker() {
                    if (this.pointList.length === 0) return;

                    this.startMarker = new AMap.Marker({
                        map: this.map,
                        position: this.pointList[0],
                        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                        offset: new AMap.Pixel(-13, -30)
                    });
                }

                // 初始化终点标记
                initEndMarker() {
                    if (this.pointList.length === 0) return;

                    this.endMarker = new AMap.Marker({
                        map: this.map,
                        position: this.pointList[this.pointList.length - 1],
                        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
                        offset: new AMap.Pixel(-13, -30)
                    });
                }

                // 开始播放
                play() {
                    if (!this.path.length) return;

                    const lastPoint = this.path[this.path.length - 1];
                    if (!lastPoint) return;

                    if (this.timeSliderPosition &&
                        this.timeSliderPosition.lng === lastPoint.lng &&
                        this.timeSliderPosition.lat === lastPoint.lat &&
                        this.timeSliderPosition.trackTime === lastPoint.trackTime) {
                        // 重新开始播放
                        this.isStartPolyLine = false;
                    }

                    this.navgStatus = 'playing';

                    if (!this.isStartPolyLine) {
                        if (this.endMarker) {
                            this.map.remove(this.endMarker);
                        }
                        this.isStartPolyLine = true;
                        this.startNavg();
                    } else {
                        if (this.navg1) {
                            this.navg1.resume();
                        } else {
                            this.startNavg();
                        }
                    }
                }

                // 开始巡航
                startNavg() {
                    if (this.navg1) {
                        this.navg1.start();
                    }
                }

                // 暂停
                pause() {
                    if (this.navg1) {
                        this.navg1.pause();
                        this.navgStatus = 'paused';
                    }
                }

                // 停止
                stop() {
                    if (this.navg1) {
                        this.navg1.stop();
                        this.navgStatus = 'default';
                        this.curIdx = 0;
                    }
                }

                // 设置速度为x倍
                setSpeed(speed) {
                    if (this.navg1) {
                        this.navg1.setSpeed(speed * 100);
                    }
                }

                // 时间轴变化
                onTimeStampChange(value) {
                    const idx = parseInt(value);
                    if (idx >= 0 && idx < this.path.length) {
                        this.curIdx = idx;
                        this.timeSliderPosition = this.path[this.curIdx];

                        if (this.navg1) {
                            this.navg1.moveToPoint(this.curIdx);
                        }

                        this.pause();
                    }
                }

                // 初始化控制面板
                initControls() {
                    document.getElementById('playBtn').addEventListener('click', () => this.play());
                    document.getElementById('pauseBtn').addEventListener('click', () => this.pause());
                    document.getElementById('stopBtn').addEventListener('click', () => this.stop());

                    document.getElementById('speedSelect').addEventListener('change', (e) => {
                        this.setSpeed(parseInt(e.target.value));
                    });

                    document.getElementById('timeSlider').addEventListener('input', (e) => {
                        const max = parseInt(e.target.max);
                        const value = parseInt(e.target.value);
                        const idx = Math.floor(value / max * (this.path.length - 1));
                        this.onTimeStampChange(idx);
                    });
                }
            }


        })




    </script>
</body>

</html>